package work.hashmap;

import java.util.HashMap;

public class Problem560 {
    public int subarraySum(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        //初始化前缀和
        map.put(0, 1);
        int sum = 0, ans = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (map.containsKey(sum - k)) {
                ans = ans + map.get(sum - k);
            }
            map.put(sum, map.getOrDefault(sum, 1) + 1);
        }
        return ans;
    }

    public static void main(String[] args) {
        Problem560 solution = new Problem560();
        int[] nums = {-1, -1, 1};
        int k = 0; // 你可以根据需要更改 k 的值
        int result = solution.subarraySum1(nums, k);
        System.out.println("Number of subarrays with sum " + k + ": " + result);
    }

    public int subarraySum1(int[] nums, int k) {
        int ans = 0;
        int sum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (map.containsKey(sum - k)) ans = ans + map.get(sum - k);
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
        return ans;
    }
}
